<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="mainor_form">
        <div class="mainor_te">
          <router-link to="/purchasing/purchase/add" class="mainor_tea"
            >备货采购</router-link
          >
          <el-button @click="exportb">导出</el-button>
          <el-button @click="dialogFormVisible = true">表头设置</el-button>
        </div>
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="70px"
        >
          <el-form-item label="采购方式" prop="mode">
            <el-select
              v-model.trim="form.mode"
              placeholder="采购方式"
              class="wid220"
            >
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="(modeList, index) in list.modeList"
                :key="index"
                :label="modeList"
                :value="parseInt(index)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单号" prop="order_sn">
            <el-input
              v-model.trim="form.order_sn"
              placeholder="单号"
              clearable
              class="wid220"
            ></el-input>
          </el-form-item>
          <el-form-item label="采购日期" prop="createTime">
            <el-date-picker
              v-model="createTime"
              type="daterange"
              class="time220"
              :editable="false"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :clearable="false"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <div class="more el-form-item" @click="more">
            <span>更多</span>
            <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
          </div>
          <div class="clearfix"></div>
          <el-collapse-transition>
            <div v-if="moredata">
              <el-form-item label="创建日期" prop="establishTime">
                <el-date-picker
                  v-model="establishTime"
                  type="daterange"
                  class="time220"
                  :editable="false"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  :picker-options="pickerOptions"
                />
              </el-form-item>
              <el-form-item label="单据状态" prop="status">
                <el-select
                  v-model.trim="form.status"
                  placeholder="单据状态"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(statusList, index) in list.statusList"
                    :key="index"
                    :label="statusList"
                    :value="parseInt(index + 1)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="采购员" prop="buyer_id">
                <el-select
                  v-model.trim="form.buyer_id"
                  placeholder="采购员"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(buyer, index) in list.buyer"
                    :key="index"
                    :label="buyer"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="供应商" prop="supplier_id">
                <el-select
                  v-model.trim="form.supplier_id"
                  placeholder="供应商"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(supplier, index) in list.supplier"
                    :key="index"
                    :label="supplier"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="单据类型" prop="type">
                <el-select
                  v-model.trim="form.type"
                  placeholder="单据类型"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(typeList, index) in list.typeList"
                    :key="index"
                    :label="typeList"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="结算状态" prop="pay_status">
                <el-select
                  v-model.trim="form.pay_status"
                  placeholder="结算状态"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(pay_status_list, index) in list.pay_status_list"
                    :key="index"
                    :label="pay_status_list"
                    :value="parseInt(index + 1)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-collapse-transition>
          <div class="clearfix"></div>
          <el-form-item class="marginTop10">
            <el-button
              class="reset marginLeft10"
              type="primary"
              @click="
                $refs['userListFrom'].resetFields(),
                  (createTime = []),
                  (establishTime = [])
              "
              >重置</el-button
            >
            <el-button
              type="primary"
              @click="getArticleList"
              :loading="listLoading"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="main_num boxdq">
        <div class="main_num_l box">
          <p>
            采购单数量：
            <em>{{ list.all }}</em>
          </p>
          <p>
            采购金额：
            <em>{{ list.all_money }}</em>
          </p>
          <p class="box" style="width: 400px; align-items: center">
            采购进度：
            <el-progress
              :text-inside="true"
              :stroke-width="15"
              :percentage="list.percent"
              status="success"
              color="#E47C02"
              style="width: 60%"
            ></el-progress>
          </p>
        </div>
        <div class="main_num_r box">
          <p @click="batch(1)">
            <el-button>
              <div class="box">
                合并采购单
                <div
                  class="mainsu_te marginLeft5"
                  style="position: relative; margin-top: -3px"
                >
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">
                      注释：同一采购日期、采购方式、采购员或供应商，并且单据状态是待采购的才能合并
                    </div>
                    <svg
                      aria-hidden="true"
                      class="navbar_svg"
                      width="16"
                      height="16"
                    >
                      <use xlink:href="#icon-summary_question" />
                    </svg>
                  </el-tooltip>
                </div>
              </div>
            </el-button>
          </p>
          <p @click="batch(2)">
            <el-button>批量取消</el-button>
          </p>
        </div>
      </div>
      <div class="main_table" style="min-height: 570px">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <div v-for="(field, index) in list.field" :key="index">
            <el-table-column
              label="采购单号"
              prop="order_sn"
              width="200"
              :show-overflow-tooltip="true"
              v-if="field == 1"
            />
            <el-table-column
              label="采购方式"
              prop="goods_code"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 2"
            >
              <template slot-scope="scope">{{
                list.modeList[scope.row.mode]
              }}</template>
            </el-table-column>
            <el-table-column
              label="采购员/供应商"
              prop="market"
              width="180"
              :show-overflow-tooltip="true"
              v-if="field == 3"
            >
              <template slot-scope="scope">{{
                scope.row.mode == 1
                  ? list.buyer[scope.row.buyer_id]
                  : list.supplier[scope.row.supplier_id]
              }}</template>
            </el-table-column>
            <el-table-column
              label="类型"
              prop="status"
              width="120"
              :show-overflow-tooltip="true"
              v-if="field == 4"
            >
              <template slot-scope="scope">{{
                list.typeList[scope.row.type]
              }}</template>
            </el-table-column>
            <el-table-column
              label="状态"
              prop="status"
              :show-overflow-tooltip="true"
              v-if="field == 5"
            >
              <template slot-scope="scope">{{
                list.statusList[scope.row.status]
              }}</template>
            </el-table-column>
            <el-table-column
              label="采购金额"
              prop="money"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 6"
            />
            <el-table-column
              label="结算状态"
              prop="status"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 7"
            >
              <template slot-scope="scope">{{
                list.pay_status_list[scope.row.pay_status]
              }}</template>
            </el-table-column>
            <el-table-column
              label="创建日期"
              prop="status"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 8"
            >
              <template slot-scope="scope">
                {{ parseTime(scope.row.created_at, "{y}-{m}-{d}") }}
              </template>
            </el-table-column>
            <el-table-column
              label="采购日期"
              prop="status"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 9"
            >
              <template slot-scope="scope">
                {{ parseTime(scope.row.purchase_time, "{y}-{m}-{d}") }}
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              prop="remark"
              :show-overflow-tooltip="true"
              v-if="field == 10"
            />
            <el-table-column
              label="采购品种"
              prop="cg"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 11"
            />
            <el-table-column
              label="已采购品种"
              prop="yc"
              width="160"
              :show-overflow-tooltip="true"
              v-if="field == 12"
            />
            <el-table-column
              label="采购进度"
              width="200"
              :show-overflow-tooltip="true"
              v-if="field == 13"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-progress
                  :text-inside="true"
                  :stroke-width="15"
                  :percentage="scope.row.jd"
                  status="success"
                  color="#03A98E"
                ></el-progress>
              </template>
            </el-table-column>
          </div>
          <el-table-column
            label="管理操作"
            align="center"
            fixed="right"
            width="300"
            class-name="main_hei"
          >
            <template slot-scope="scope">
              <router-link
                :to="'/purchasing/purchase/record/' + scope.row.id"
                v-if="scope.row.status == 0 || scope.row.status == 1"
              >
                <el-link type="warning">录单</el-link>
              </router-link>
              <router-link :to="'/purchasing/purchase/see/' + scope.row.id">
                <el-link type="success">查看</el-link>
              </router-link>
              <router-link
                :to="
                  scope.row.type == 1
                    ? ''
                    : '/purchasing/purchase/edit/' + scope.row.id
                "
                v-if="scope.row.status == 0 && scope.row.type == 2"
              >
                <el-link :type="scope.row.type == 1 ? 'info' : 'primary'"
                  >编辑</el-link
                >
              </router-link>
              <el-link>打印</el-link>
              <el-link
                type="danger"
                @click="delet(scope.row.id)"
                v-if="scope.row.status == 0"
                >取消</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <el-pagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <el-dialog
      title="表头设置"
      :visible.sync="dialogFormVisible"
      class="main_dialog dialog500"
      @close="type = list.field"
    >
      <el-checkbox-group v-model="type">
        <el-checkbox
          v-for="(Header, index) in Header"
          :key="index"
          :label="Header.id"
          :disabled="Header.disabled"
          >{{ Header.name }}</el-checkbox
        >
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="setupmine" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!--采购单导出  -->
    <el-dialog
      title="订单导出"
      :visible.sync="exportbuVisible"
      class="main_dialog dialog500"
    >
      <div v-if="selectArr.length == 0 ? true : false">
        <p class="exptitle">选择导出时间</p>
        <el-date-picker
          v-model="exportTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="datepicker"
        >
        </el-date-picker>
        <el-tooltip
          class="item"
          effect="dark"
          content="Top Center 提示文字"
          placement="top"
        >
          <i class="el-icon-question"></i>
        </el-tooltip>
      </div>
      <div v-if="goodspicker">
        <p class="exptitle margintop">选择导出商品字段信息</p>
        <el-checkbox-group v-model="exportHeaderType.goodsList">
          <el-checkbox
            v-for="(Header, index) in exportGoodsList"
            :key="index"
            :label="Header.id"
            :disabled="Header.disabled"
            >{{ Header.name }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportbuVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportConfirm" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLodop } from "@/utils/LodopFuncs";
import {
  purchase_index,
  purchase_merge,
  purchase_cancel,
  purchase_cancelList,
  export_head_info,
  export_purchase_list,
} from "@/api/purchasing/purchasingPurchase";
import { field_save } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import dateOption from "@/options/dateOption";
import { parseTime } from "@/utils/index";
import exportList from "@/options/export";
import { order_export } from "@/api/order/orderList";

export default {
  directives: {
    // 聚焦元素
    focus: {
      inserted(el) {
        el.querySelector("input").focus();
      },
    },
  },
  data() {
    return {
      // 时间
      parseTime,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {
        create_start_time: "",
        create_end_time: "",
        start_time: "",
        end_time: "",
        mode: null,
        order_sn: "",
        storehouse_id: null,
        status: null,
        buyer_id: null,
        supplier_id: null,
        type: null,
        pay_status: null,
      },
      createTime: [],
      establishTime: [],
      pickerOptions: dateOption,
      // 更多
      moredata: false,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      listLoading: false,
      // 全选
      selectArr: [],
      // 表头设置
      dialogFormVisible: false,
      type: [],
      Header: [
        {
          id: 1,
          name: "采购单号",
          disabled: true,
        },
        {
          id: 2,
          name: "采购方式",
          disabled: false,
        },
        {
          id: 3,
          name: "采购员/供应商",
          disabled: false,
        },
        {
          id: 4,
          name: "类型",
          disabled: false,
        },
        {
          id: 5,
          name: "状态",
          disabled: false,
        },
        {
          id: 6,
          name: "采购金额",
          disabled: false,
        },
        {
          id: 7,
          name: "结算状态",
          disabled: false,
        },
        {
          id: 8,
          name: "创建日期",
          disabled: false,
        },
        {
          id: 9,
          name: "采购日期",
          disabled: true,
        },
        {
          id: 10,
          name: "备注",
          disabled: false,
        },
        {
          id: 11,
          name: "采购品种",
          disabled: false,
        },
        {
          id: 12,
          name: "已采购品种",
          disabled: false,
        },
        {
          id: 13,
          name: "采购进度",
          disabled: false,
        },
      ],

      // 采购单导出
      exportbuVisible: false,
      goodspicker: true, //商品信息 true
      exportGoodsList: exportList.purchaseHeadList,
      // 默认的导出表头信息
      exportHeaderType: {
        goodsList: [],
      },
      // 订单导出时间
      exportTime: [],
    };
  },
  // 刷新
  inject: ["reload"],
  methods: {
    // 批量
    batch(type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { ids: JSON.stringify(this.selectArr) }
      );
      if (this.selectArr.length != 0) {
        if (type == 1) {
          this.$confirm(
            "已选择" + this.selectArr.length + "个采购单，确定合并吗?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              purchase_merge(data).then((res) => {
                if (res.errcode == 0) {
                  this.$message({
                    message: "合并成功",
                    type: "success",
                  });
                  this.purchase_index();
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            })
            .catch(() => {});
        } else {
          this.$confirm(
            "已选择" +
              this.selectArr.length +
              "个采购单，取消后不能恢复，确定取消吗?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
            .then(() => {
              purchase_cancel(data).then((res) => {
                if (res.errcode == 0) {
                  this.$message({
                    message: "取消成功",
                    type: "success",
                  });
                  this.purchase_index();
                } else {
                  this.$message.error(res.errmsg);
                }
              });
            })
            .catch(() => {});
        }
      } else {
        this.$message.error("请勾选采购单");
      }
    },
    // 导出
    exportb() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      export_head_info(data).then((res) => {
        if (res.errcode == 0) {
          this.exportHeaderType.goodsList = res.data.list.type_12;
        }
        this.exportbuVisible = true;
      });
    },
    // 导出时间范围
    datepicker(val) {
      let start = "";
      let end = "";
      if (val) {
        start = new Date(val[0]).getTime();
        end = new Date(val[1]).getTime();
        if(end - start > 30*24*60*1000) {
          this.$message.error('选择范围不能超过一个月，请重新选择')
          this.exportTime = '';
        }
      }
    },
    // 导出确认
    exportConfirm() {
      let goodsList = [];
      this.exportGoodsList.map((e) => {
        this.exportHeaderType.goodsList.map((p) => {
          if (e.id == p) {
            goodsList.push(e.id);
            return;
          }
        });
      });
      let ids = [];
      if (this.selectArr.length > 0) {
        this.selectArr.forEach((item) => {
          ids.push(item.id);
        });
        this.exportTime = "";
      }
      let time = "";
      if (this.exportTime) {
        time = this.exportTime.join(" ");
      }
      let form = {
        ids: ids.join("-"),
        list_head: goodsList.join("-"),
        send_time: time,
      };

      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      if (!data.send_time && !data.ids) {
        this.$message.warning("请选择导出的时间段或导出的订单");
        return false;
      }
      let data1 = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { type: 12 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          type: 12,
          fields: JSON.stringify(goodsList),
        }
      );
      field_save(data1).then((res) => {
        if (res.errcode != 0) {
          this.$message.error("导出表头设置失败");
        }
      });
      export_purchase_list(data).then((res) => {
        const link = document.createElement("a");
        let blob = new Blob([res], { type: "application/vnd.ms-excel" });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
      this.exportbuVisible = false;
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
      console.log(this.selectArr);
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.purchase_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.purchase_index();
    },
    changePage(page) {
      this.current.page = page;
      this.purchase_index();
    },
    // 设置确认
    setupmine(val) {
      let arry = [];
      this.Header.map((e) => {
        this.type.map((p) => {
          if (e.id == p) {
            arry.push(e.id);
            return;
          }
        });
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { type: 7 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { type: 7, fields: JSON.stringify(arry) }
        // [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
      );
      field_save(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "设置成功",
            type: "success",
          });
          this.reload();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 取消
    delet(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      this.$confirm("是否取消采购单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          purchase_cancelList(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "取消成功",
                type: "success",
              });
              this.purchase_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 列表
    purchase_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      purchase_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.type = res.data.field;
          res.data.list.data.map((e) => {
            e.cg = e.purchase_list.length;
            let gs = 0;
            e.purchase_list.map((p) => {
              if (p.status == 1) {
                gs++;
              }
            });
            e.yc = gs;
            e.jd = parseInt((gs / e.purchase_list.length) * 100);
          });
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      form.create_start_time = this.establishTime[0]
        ? this.establishTime[0]
        : "";
      form.create_end_time = this.establishTime[1] ? this.establishTime[1] : "";

      return form;
    },
  },
  created() {
    // 列表
    this.purchase_index();
  },
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 240px);
}

// 导出订单表头
.exptitle {
  display: block;
  font-size: 16px;
  color: #000000;
  margin: 0 0 10px;
}
.margintop {
  padding-top: 15px;
}
.el-checkbox-group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .el-checkbox {
    width: 26%;
  }
}
</style>
